package com.moinut.studentattendancemanager.controller;

import com.moinut.studentattendancemanager.config.UserType;
import com.moinut.studentattendancemanager.controller.callback.OnUpdateListener;
import com.moinut.studentattendancemanager.model.factory.DAOFactory;
import com.moinut.studentattendancemanager.model.vo.db.Student;
import com.moinut.studentattendancemanager.model.vo.db.Teacher;
import com.sun.istack.internal.NotNull;

/**
 * @author MOILING
 */
public class PasswordController {

    public static void updatePassword(@NotNull UserType type, @NotNull String oldId, @NotNull String oldPassword,
                                      @NotNull String newPassword, @NotNull String confirmPassword, @NotNull OnUpdateListener listener) {
        if (oldPassword.isEmpty()) {
            listener.onError("原始密码不能为空");
        } else if (newPassword.isEmpty()) {
            listener.onError("新密码不能为空");
        } else if (confirmPassword.isEmpty()) {
            listener.onError("确认密码不能为空");
        } else if (!newPassword.equals(confirmPassword)) {
            listener.onError("两次密码输入不同");
        } else if (type == UserType.TYPE_STUDENT) {
            try {
                if (DAOFactory.getIStudentDAOInstance().findLogin(new Student(oldId, oldPassword)) != null) {
                    if (DAOFactory.getIStudentDAOInstance().updateStudentPassword(oldId, newPassword)) {
                        listener.onSuccess("修改密码成功");
                    } else {
                        listener.onError("修改密码失败");
                    }
                } else {
                    listener.onError("原始密码错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.onError(e.getMessage());
            }
        } else if (type == UserType.TYPE_TEACHER) {
            try {
                if (DAOFactory.getITeacherDAOInstance().findLogin(new Teacher(oldId, oldPassword)) != null) {
                    if (DAOFactory.getITeacherDAOInstance().updateTeacherPassword(oldId, newPassword)) {
                        listener.onSuccess("修改密码成功");
                    } else {
                        listener.onError("修改密码失败");
                    }
                } else {
                    listener.onError("原始密码错误");
                }
            } catch (Exception e) {
                e.printStackTrace();
                listener.onError(e.getMessage());
            }
        }
    }
}
